package mblog.core.persist.service.impl;

import mblog.core.data.PMaterial;
import mblog.core.persist.dao.MaterialDao;
import mblog.core.persist.entity.PMaterialPO;
import mblog.core.persist.service.MaterialService;
import mtons.modules.pojos.Paging;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Beldon 2015/10/25
 */
@Service
@Transactional
public class MaterialServiceImpl implements MaterialService {

    @Autowired
    private MaterialDao materialDao;

    @Override
    public void save(PMaterial material) {
        PMaterialPO materialPO = new PMaterialPO();

        BeanUtils.copyProperties(material, materialPO);

        materialDao.saveOrUpdate(materialPO);

    }

    @Override
    public void delete(long id) {
        PMaterialPO po = materialDao.get(id);
       // materialDao.delete(po);
        po.setIsDel(1);
        materialDao.update(po);
    }

    @Override
    public PMaterial findById(long id) {
        PMaterialPO materialPO = materialDao.get(id);
        PMaterial material = new PMaterial();
        BeanUtils.copyProperties(materialPO,material);
        return material;
    }

    @Override
    public List<PMaterial> findAll() {

        List<PMaterialPO> linkPOs = materialDao.findAll();

        List<PMaterial> rets = new ArrayList<PMaterial>();
        for (PMaterialPO po : linkPOs) {
            PMaterial m = new PMaterial();
            BeanUtils.copyProperties(po, m);
            rets.add(m);
        }
        return rets;
    }

    @Override
    public void paging(Paging paging, String key) {
        List<PMaterialPO> list = materialDao.paging(paging,key);
        List<PMaterial> rets = new ArrayList<>();
        for (PMaterialPO po : list) {
            PMaterial u = new  PMaterial();
            BeanUtils.copyProperties(po ,u);
            rets.add(u);
        }
        paging.setResults(rets);
    }


    public List<PMaterial> getByNameAndModel(String name, String model){
        List<PMaterialPO> list = materialDao.getByNameAndModel(name,model);
        List<PMaterial> rets = new ArrayList<PMaterial>();
        for (PMaterialPO po : list) {
            PMaterial u = new  PMaterial();
            BeanUtils.copyProperties(po ,u);
            rets.add(u);
        }
        return rets;
    }

}
